from django.db import models
from django.contrib.auth.models import User
from django.utils.timezone import now


class PostQuerySet(models.query.QuerySet):
    """Custom queryset for posts that snippets additional methods"""

    def published(self):
        return self.filter(published__lte=now())

    def unpublished(self):
        return self.filter(published=None)

    def pending(self):
        return self.filter(published__gt=now())


class PostManager(models.Manager):
    def get_query_set(self):
        return PostQuerySet(self.model)

# Models
class Tag(models.Model):
    name = models.CharField(max_length=255, unique=True)

    def __unicode__(self):
        return self.name


class BaseContentModel(models.Model):
    """Base abstract model for content types"""
    title = models.CharField(max_length=255, blank=False,
                             verbose_name=u"Title")
    creator = models.ForeignKey(User, verbose_name=u"Author")
    # Dates
    created = models.DateTimeField(auto_now_add=True,
                                   verbose_name=u"Created")
    published = models.DateTimeField(verbose_name=u"Published",
                                     blank=True,
                                     null=True)
    modified = models.DateTimeField(auto_now=True, auto_now_add=True,
                                    verbose_name=u"Last modified")

    class Meta:
        abstract = True


class Post(BaseContentModel):
    # Fields start here
    body = models.TextField(blank=True, verbose_name="Content body")
    tags = models.ManyToManyField(Tag, blank=True, verbose_name="Tags")

    # Custom managers
    objects = PostManager()

    def __unicode__(self):
        return self.title

    @property
    def has_tags(self):
        return True if self.tags.count() else False

    @property
    def is_published(self):
        return self.published <= now() if self.published else False



